package com.zhang.webadmin.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhang.webadmin.pojo.AclUser;
import com.zhang.webadmin.pojo.AclUserLoginToken;
import com.zhang.webadmin.service.AclUserLoginTokenService;
import com.zhang.webadmin.util.R;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.UUID;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private AclUserLoginTokenService aclUserLoginTokenService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");

        AclUser aclUser = (AclUser) authentication.getPrincipal();

        AclUserLoginToken loginToken = new AclUserLoginToken();
        loginToken.setUid(aclUser.getId());
        loginToken.setToken(UUID.randomUUID().toString());
        loginToken.setCreateTime(LocalDateTime.now());
        loginToken.setUpdateTime(LocalDateTime.now());
        aclUserLoginTokenService.save(loginToken);

        R r = R.ok(loginToken.getToken());
        response.getWriter().write(objectMapper.writeValueAsString(r));
    }
}
